package com.example.hello.service.impl;

import com.example.hello.dto.AttractionDTO;
import com.example.hello.entity.Attraction;
import com.example.hello.entity.Category;
import com.example.hello.mapper.AttractionMapper;
import com.example.hello.mapper.CategoryMapper;
import com.example.hello.service.AttractionService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class AttractionServiceImpl implements AttractionService {

    private static final Logger logger = LogManager.getLogger(AttractionServiceImpl.class);

    @Autowired
    private AttractionMapper attractionMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    @Transactional
    public boolean addAttraction(AttractionDTO attractionDTO, Long userId) {
        // 验证分类是否存在
        Category category = categoryMapper.getCategoryById(attractionDTO.getCategoryId());
        if (category == null) {
            throw new RuntimeException("所选景点分类不存在");
        }

        // 检查景点名称是否已存在
        Attraction existAttraction = attractionMapper.getAttractionByName(attractionDTO.getName());
        if (existAttraction != null) {
            throw new RuntimeException("景点名称已存在");
        }

        // 设置默认值
        Attraction attraction = new Attraction();
        BeanUtils.copyProperties(attractionDTO, attraction);
        
        // 确保有默认值
        if (attraction.getStatus() == null) {
            attraction.setStatus(0); // 0-待审核 1-正常 2-下架
        }
        if (attraction.getCoverImages() == null) {
            attraction.setCoverImages(new ArrayList<>());
        }
        if (attraction.getTags() == null) {
            attraction.setTags(new ArrayList<>());
        }
        
        // 设置创建者
        attraction.setCreatedBy(userId);

        return attractionMapper.insertAttraction(attraction) > 0;
    }

    @Override
    @Transactional
    public boolean updateAttraction(AttractionDTO attractionDTO) {
        // 检查景点是否存在
        Attraction existAttraction = attractionMapper.getAttractionById(attractionDTO.getAttractionId());
        if (existAttraction == null) {
            throw new RuntimeException("景点不存在");
        }

        // 如果更改了分类，验证新分类是否存在
        if (attractionDTO.getCategoryId() != null && !attractionDTO.getCategoryId().equals(existAttraction.getCategoryId())) {
            Category category = categoryMapper.getCategoryById(attractionDTO.getCategoryId());
            if (category == null) {
                throw new RuntimeException("所选景点分类不存在");
            }
        }

        // 如果更改了名称，检查新名称是否被其他景点占用
        if (attractionDTO.getName() != null && !attractionDTO.getName().equals(existAttraction.getName())) {
            Attraction nameExistAttraction = attractionMapper.getAttractionByName(attractionDTO.getName());
            if (nameExistAttraction != null) {
                throw new RuntimeException("景点名称已存在");
            }
        }

        // 更新景点信息
        Attraction attraction = new Attraction();
        BeanUtils.copyProperties(attractionDTO, attraction);

        return attractionMapper.updateAttraction(attraction) > 0;
    }

    @Override
    @Transactional
    public boolean deleteAttraction(Long attractionId) {
        // 检查景点是否存在
        Attraction existAttraction = attractionMapper.getAttractionById(attractionId);
        if (existAttraction == null) {
            throw new RuntimeException("景点不存在");
        }

        // TODO: 检查是否有评论、收藏等关联数据，有关联数据时应该考虑级联删除或禁止删除

        return attractionMapper.deleteAttractionById(attractionId) > 0;
    }

    @Override
    public Attraction getAttractionById(Long attractionId) {
        return attractionMapper.getAttractionById(attractionId);
    }

    @Override
    public PageInfo<Attraction> getAttractionList(Attraction attraction, Integer pageNum, Integer pageSize) {
        try {
            logger.info("开始查询景点列表，参数：{}, 页码：{}, 每页数量：{}", attraction, pageNum, pageSize);
            PageHelper.startPage(pageNum, pageSize);
            List<Attraction> list = attractionMapper.getAttractionList(attraction);
            logger.info("查询景点列表成功，共获取 {} 条记录", list.size());
            return new PageInfo<>(list);
        } catch (Exception e) {
            logger.error("查询景点列表失败", e);
            // 重新抛出异常，但已记录详细日志
            throw new RuntimeException("查询景点列表失败: " + e.getMessage(), e);
        }
    }

    @Override
    @Transactional
    public boolean incrementViewCount(Long attractionId) {
        return attractionMapper.incrementViewCount(attractionId) > 0;
    }
} 